<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="日历视图" 
      :show-back="true"
    />
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <!-- 年月选择器 -->
      <view class="date-selector">
        <view class="selector-item" @click="showYearPicker = true">
          <text class="selector-text">{{ currentYear }}年</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
        <view class="selector-item" @click="showMonthPicker = true">
          <text class="selector-text">{{ currentMonth }}月</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
        <view class="today-btn" @click="goToToday">
          <text class="today-text">今天</text>
        </view>
      </view>
      
      <!-- 日历组件 -->
      <view class="calendar-container">
        <!-- 星期标题 -->
        <view class="week-header">
          <view class="week-item" v-for="week in weekDays" :key="week">
            <text class="week-text">{{ week }}</text>
          </view>
        </view>
        
        <!-- 日历网格 -->
        <view class="calendar-grid">
          <view 
            class="calendar-day" 
            v-for="day in calendarDays" 
            :key="day.key"
            :class="{
              'other-month': !day.isCurrentMonth,
              'today': day.isToday,
              'has-diary': day.hasDiary,
              'selected': day.isSelected
            }"
            @click="selectDate(day)"
          >
            <text class="day-number">{{ day.day }}</text>
            <view class="diary-indicator" v-if="day.hasDiary">
              <view 
                class="indicator-dot" 
                v-for="(diary, index) in day.diaries.slice(0, 3)" 
                :key="index"
                :style="{ backgroundColor: getDiaryColor(diary) }"
              ></view>
              <text class="diary-count" v-if="day.diaries.length > 3">
                +{{ day.diaries.length - 3 }}
              </text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 选中日期的日记列表 -->
      <view class="selected-date-diaries" v-if="selectedDateDiaries.length > 0">
        <view class="section-title">
          <text class="title-text">{{ formatDate(selectedDate) }} 的日记</text>
          <text class="count-text">共 {{ selectedDateDiaries.length }} 篇</text>
        </view>
        
        <scroll-view scroll-y class="diaries-scroll">
          <view 
            class="diary-item" 
            v-for="diary in selectedDateDiaries" 
            :key="diary.id"
            @click="goToDiaryDetail(diary.id)"
          >
            <view class="diary-header">
              <text class="diary-title">{{ diary.title }}</text>
              <text class="diary-time">{{ formatTime(diary.createdAt) }}</text>
            </view>
            <text class="diary-content">{{ diary.content }}</text>
            <view class="diary-meta" v-if="diary.mood || diary.weather">
              <text class="meta-item" v-if="diary.mood">{{ diary.mood }}</text>
              <text class="meta-item" v-if="diary.weather">{{ diary.weather }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-date" v-else-if="selectedDate">
        <EmptyState 
          type="diary" 
          title="这天还没有日记"
          description="点击下方按钮开始记录这一天"
          button-text="写日记"
          @buttonClick="writeForDate"
        />
      </view>
    </view>
    
    <!-- 年份选择器 -->
    <picker 
      mode="date" 
      fields="year"
      :value="currentYear + '-01-01'"
      @change="onYearChange"
      v-if="showYearPicker"
    ></picker>
    
    <!-- 月份选择器 -->
    <picker 
      mode="date" 
      fields="month"
      :value="currentYear + '-' + String(currentMonth).padStart(2, '0') + '-01'"
      @change="onMonthChange"
      v-if="showMonthPicker"
    ></picker>
    
    <!-- 写日记按钮 -->
    <view class="fab-container">
      <view class="fab-btn bg-primary" @click="goToWrite">
        <uni-icons type="plus" size="24" color="#ffffff"></uni-icons>
      </view>
    </view>
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading" text="加载中..." />
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { useDiaryStore } from '@/store/diary'
import { getCalendarStatsAPI } from '@/api/statistics'
import { getDiariesAPI } from '@/api/diary'
import { formatDate, formatDateTime, extractResponseData } from '@/utils/index'
import EmptyState from '@/components/EmptyState.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'
import CustomNavBar from '@/components/CustomNavBar.vue'

export default {
  name: 'CalendarPage',
  components: {
    EmptyState,
    LoadingComponent,
    CustomNavBar
  },
  setup() {
    const userStore = useUserStore()
    const diaryStore = useDiaryStore()
    
    return {
      userStore,
      diaryStore,
      formatDate,
      formatDateTime
    }
  },
  data() {
    const now = new Date()
    return {
      loading: false,
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1,
      selectedDate: null,
      showYearPicker: false,
      showMonthPicker: false,
      
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarData: {},
      selectedDateDiaries: []
    }
  },
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    },
    
    calendarDays() {
      const year = this.currentYear
      const month = this.currentMonth
      const firstDay = new Date(year, month - 1, 1)
      const lastDay = new Date(year, month, 0)
      const daysInMonth = lastDay.getDate()
      const startWeekDay = firstDay.getDay()
      
      const days = []
      const today = new Date()
      const todayStr = formatDate(today)
      
      // 上个月的日期
      const prevMonth = month === 1 ? 12 : month - 1
      const prevYear = month === 1 ? year - 1 : year
      const prevLastDay = new Date(prevYear, prevMonth, 0).getDate()
      
      for (let i = startWeekDay - 1; i >= 0; i--) {
        const day = prevLastDay - i
        const dateStr = formatDate(new Date(prevYear, prevMonth - 1, day))
        days.push({
          key: `prev-${day}`,
          day,
          date: dateStr,
          isCurrentMonth: false,
          isToday: false,
          hasDiary: this.calendarData[dateStr]?.length > 0,
          diaries: this.calendarData[dateStr] || [],
          isSelected: this.selectedDate === dateStr
        })
      }
      
      // 当前月的日期
      for (let day = 1; day <= daysInMonth; day++) {
        const dateStr = formatDate(new Date(year, month - 1, day))
        days.push({
          key: `current-${day}`,
          day,
          date: dateStr,
          isCurrentMonth: true,
          isToday: dateStr === todayStr,
          hasDiary: this.calendarData[dateStr]?.length > 0,
          diaries: this.calendarData[dateStr] || [],
          isSelected: this.selectedDate === dateStr
        })
      }
      
      // 下个月的日期（补齐6行）
      const totalDays = days.length
      const remainingDays = 42 - totalDays // 6行 × 7列
      const nextMonth = month === 12 ? 1 : month + 1
      const nextYear = month === 12 ? year + 1 : year
      
      for (let day = 1; day <= remainingDays; day++) {
        const dateStr = formatDate(new Date(nextYear, nextMonth - 1, day))
        days.push({
          key: `next-${day}`,
          day,
          date: dateStr,
          isCurrentMonth: false,
          isToday: false,
          hasDiary: this.calendarData[dateStr]?.length > 0,
          diaries: this.calendarData[dateStr] || [],
          isSelected: this.selectedDate === dateStr
        })
      }
      
      return days
    }
  },
  onLoad() {
    this.initPage()
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 加载日历数据
      await this.loadCalendarData()
    },
    
    async loadCalendarData() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const res = await getCalendarStatsAPI({
          year: this.currentYear,
          month: this.currentMonth
        })
        
        const data = extractResponseData(res)
        this.calendarData = data || {}
        
      } catch (error) {
        console.error('加载日历数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 选择日期
    selectDate(day) {
      this.selectedDate = day.date
      this.selectedDateDiaries = day.diaries
    },
    
    // 跳转到今天
    goToToday() {
      const today = new Date()
      this.currentYear = today.getFullYear()
      this.currentMonth = today.getMonth() + 1
      this.selectedDate = formatDate(today)
      this.loadCalendarData()
    },
    
    // 年份改变
    onYearChange(e) {
      this.currentYear = parseInt(e.detail.value.split('-')[0])
      this.showYearPicker = false
      this.loadCalendarData()
    },
    
    // 月份改变
    onMonthChange(e) {
      const [year, month] = e.detail.value.split('-')
      this.currentYear = parseInt(year)
      this.currentMonth = parseInt(month)
      this.showMonthPicker = false
      this.loadCalendarData()
    },
    
    // 获取日记颜色
    getDiaryColor(diary) {
      if (diary.category) {
        return diary.category.color || '#1890ff'
      }
      return '#1890ff'
    },
    
    // 格式化时间
    formatTime(datetime) {
      return formatDateTime(datetime, 'HH:mm')
    },
    
    // 跳转到日记详情
    goToDiaryDetail(diaryId) {
      uni.navigateTo({
        url: `/pages/diary/detail?id=${diaryId}`
      })
    },
    
    // 为选中日期写日记
    writeForDate() {
      uni.navigateTo({
        url: `/pages/diary/edit?date=${this.selectedDate}`
      })
    },
    
    // 写日记
    goToWrite() {
      uni.switchTab({
        url: '/pages/diary/edit'
      })
    },
    
    // 编辑日记
    editDiary(diary) {
      // 设置编辑状态
      this.diaryStore.setEditingDiary(diary.id)
      
      // 跳转到编辑页面
      uni.switchTab({
        url: '/pages/diary/edit'
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}



.page-content {
  padding: 40rpx;
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  min-height: calc(100vh - calc(var(--status-bar-height, 44rpx) + 88rpx));
  display: flex;
  flex-direction: column;
}

.date-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 32rpx;
  padding: 32rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  background-color: #f8f8f8;
  border-radius: 20rpx;
}

.selector-text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.today-btn {
  padding: 16rpx 24rpx;
  background-color: #1890ff;
  border-radius: 20rpx;
}

.today-text {
  font-size: 28rpx;
  color: #ffffff;
}

.calendar-container {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.week-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 16rpx;
}

.week-item {
  text-align: center;
  padding: 16rpx 0;
}

.week-text {
  font-size: 24rpx;
  color: #666666;
  font-weight: 500;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
}

.calendar-day:active {
  transform: scale(0.95);
}

.calendar-day.other-month .day-number {
  color: #cccccc;
}

.calendar-day.today {
  background-color: #1890ff;
}

.calendar-day.today .day-number {
  color: #ffffff;
  font-weight: 600;
}

.calendar-day.has-diary {
  background-color: #e6f7ff;
}

.calendar-day.selected {
  background-color: #52c41a;
}

.calendar-day.selected .day-number {
  color: #ffffff;
  font-weight: 600;
}

.day-number {
  font-size: 26rpx;
  color: #333333;
  margin-bottom: 4rpx;
}

.diary-indicator {
  display: flex;
  gap: 2rpx;
  align-items: center;
}

.indicator-dot {
  width: 6rpx;
  height: 6rpx;
  border-radius: 3rpx;
  background-color: #1890ff;
}

.diary-count {
  font-size: 16rpx;
  color: #666666;
  margin-left: 2rpx;
}

.selected-date-diaries {
  flex: 1;
  background-color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 40rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.title-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.count-text {
  font-size: 24rpx;
  color: #999999;
}

.diaries-scroll {
  max-height: 400rpx;
}

.diary-item {
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;
}

.diary-item:last-child {
  border-bottom: none;
}

.diary-item:active {
  background-color: #f8f8f8;
}

.diary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.diary-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  flex: 1;
  margin-right: 16rpx;
}

.diary-time {
  font-size: 24rpx;
  color: #999999;
}

.diary-content {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.diary-meta {
  display: flex;
  gap: 16rpx;
}

.meta-item {
  font-size: 22rpx;
  color: #999999;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.empty-date {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 80rpx 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  text-align: center;
  margin-bottom: 40rpx;
}

.fab-container {
  position: fixed;
  right: 32rpx;
  bottom: 120rpx;
  z-index: 999;
}

.fab-btn {
  width: 112rpx;
  height: 112rpx;
  border-radius: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
  transition: all 0.3s;
}

.fab-btn:active {
  transform: scale(0.95);
}

.bg-primary {
  background-color: #1890ff;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .date-selector,
.theme-dark .calendar-container,
.theme-dark .selected-date-diaries,
.theme-dark .empty-date {
  background-color: #252526 !important;
}

.theme-dark .selector-item {
  background-color: #3c3c3c !important;
}

.theme-dark .selector-text,
.theme-dark .week-text,
.theme-dark .day-number,
.theme-dark .title-text,
.theme-dark .diary-title {
  color: #e8e8e8 !important;
}

.theme-dark .count-text,
.theme-dark .diary-time,
.theme-dark .diary-content {
  color: #b3b3b3 !important;
}

.theme-dark .calendar-day.other-month .day-number {
  color: #666666 !important;
}

.theme-dark .calendar-day.has-diary {
  background-color: #2d4a5c !important;
}

.theme-dark .diary-item {
  border-bottom-color: #404040 !important;
}

.theme-dark .diary-item:active {
  background-color: #2d2d30 !important;
}

.theme-dark .section-title {
  border-bottom-color: #404040 !important;
}

.theme-dark .meta-item {
  background-color: #404040 !important;
  color: #b3b3b3 !important;
}

.theme-dark .diary-count {
  color: #8c8c8c !important;
}
</style> 